package com.devilvan.betrice.export.component;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.devilvan.betrice.export.strategy.BetriceCellWriteStyle;
import com.devilvan.betrice.export.pojo.BetriceExportEntity;
import com.devilvan.betrice.export.pojo.EasyexcelWriteDto;
import com.devilvan.betrice.util.UValidAssem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Evad.Wu
 * @Description Easyexcel导出xls 组件
 * @date 2022-09-07
 */
@Slf4j
@Component
public class EasyexcelComponent {
    @Lazy
    @Resource(name = "basicWriteStrategy")
    private HorizontalCellStyleStrategy horizontalCellStyleStrategy;

    /**
     * 步骤一：根据路径、文件名、后缀、导出类型、生成excelWriter对象
     *
     * @param easyexcelWriteDto {@link EasyexcelWriteDto}
     * @return {@link ExcelWriter}
     */
    public ExcelWriter doExcelWriter(EasyexcelWriteDto easyexcelWriteDto) {
        ExcelWriter excelWriter = null;
        try {
            String exportPath = UValidAssem.validExportPath(easyexcelWriteDto.getExportPath(), easyexcelWriteDto.getFileName(), easyexcelWriteDto.getSuffix().getValue());
            // 可选：.registerWriteHandler(new SimpleColumnWidthStyleStrategy(20))
            excelWriter = EasyExcelFactory.write(exportPath)
                    .head(easyexcelWriteDto.getClassType())
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(new BetriceCellWriteStyle<>())
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return excelWriter;
    }

    /**
     * 步骤二：根据sheet生成WriteSheet对象
     *
     * @param sheet 表单名称
     * @return {@link WriteSheet}
     */
    public WriteSheet doWriteSheet(String sheet) {
        return EasyExcelFactory.writerSheet(sheet).build();
    }

    /**
     * 步骤三：装载数据导出
     *
     * @param excelWriter 导出excel的基本信息对象
     * @param writeSheet  导出excel的表单对象
     * @param exportList  导出的数据
     * @param <T>         导出数据的类型
     */
    public <T extends BetriceExportEntity> void doExport(ExcelWriter excelWriter, WriteSheet writeSheet, List<T> exportList) {
        excelWriter.write(exportList, writeSheet);
    }

    /**
     * 最后：关闭ExcelWriter
     *
     * @param excelWriter 导出流
     */
    public void doFinish(ExcelWriter excelWriter) {
        if (null != excelWriter) {
            excelWriter.close();
        }
    }
}
